package com.ray.export.runner.exports;

import com.ray.export.empty.Empty;
import com.ray.export.runner.Runner;
import com.ray.export.runner.RunnerResult;
import com.ray.export.spring.ApplicationContextUtil;
import com.ray.export.strategy.data.DataModel;
import com.ray.export.strategy.exports.DataCount;
import com.ray.export.strategy.exports.DataCountResult;
import com.ray.export.template.ExportTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

/**
 * <p>ClassName:     DataCountRunner
 * <p>Description:   数据统计执行者
 * <p>Author         jumWang
 * <p>Version        V1.0
 * <p>Date           2019.12.3
 */
@Slf4j
public class DataCountRunner implements Runner<ExportTemplate> {

    @Override
    public RunnerResult doRunner(ExportTemplate annotation, DataModel dataModel, RunnerResult perResult) {
        log.info("执行数据统计操作");
        Class<?> dataCountClass = annotation.dataCount();
        if (dataCountClass == Empty.class) {
            return new RunnerResult(Empty.class, dataModel,dataModel.getBeforeResult());
        }
        //判读配置是否符合规则
        if (!DataCount.class.isAssignableFrom(dataCountClass)) {
            log.error("数据统计操作配置错误");
            throw new RuntimeException("数据统计操作配置错误");
        }
        //获取执行对象
        DataCount dataCount = (DataCount) ApplicationContextUtil.getApplicationContext().getBean(dataCountClass);
        if (ObjectUtils.isEmpty(dataCount)) {
            log.error("获取执行对象异常[{}]", dataCountClass.getName());
            throw new RuntimeException("获取执行对象异常");
        }
        //获取结果总数
        DataCountResult dataCountResult = dataCount.count(dataModel.getExportQueryRequest());
        if (ObjectUtils.isEmpty(dataCountResult)) {
            log.error("获取结果总数失败");
            throw new RuntimeException("获取结果总数失败");
        }
        if(0 > dataCountResult.getCount()) {
            log.error("返回结果数必须大于等于0");
            throw new RuntimeException("返回结果数必须大于等于0");
        }
        dataModel.setCount(dataCountResult.getCount());
        return new RunnerResult(DataCountRunner.class, dataModel, dataCountResult);
    }

}
